package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;
    //构造方法，传入 端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while(true) {
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //为了方便在java代码种处理，可以把上述数据报中的二进制数据拿出来，构成String类
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            //2.根据请求计算相应
            String response = process(request);
            //3.把响应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
        }
    }
    //当前服务器是"回显服务器，不进行计算之类的操作,直接返回请求"
    private String process(String request) {
        return request;
    }
}
